import { app, BrowserWindow, Menu } from "electron";
import * as path from 'path';
import { format as formatUrl } from 'url';
import menuTpl from "./menuTpl";
declare const __static: string;

const isDevelopment = process.env.NODE_ENV !== 'production';

// global reference to mainWindow (necessary to prevent window from being garbage collected)
let mainWindow: BrowserWindow | null = null;



function createMainWindow(): BrowserWindow {

    const window = new BrowserWindow({
        width: 840,
        height: 600,
        webPreferences: {
            webSecurity: false
        }
    });

    if (isDevelopment) {
        window.webContents.openDevTools();
        window.loadURL(`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}`);
    } else {
        window.loadURL(formatUrl({
            pathname: path.join(__dirname, './index.html'),
            protocol: 'file',
            slashes: true
        }));
    }


    window.on('closed', () => {
        mainWindow = null;
    });

    window.webContents.on('devtools-opened', () => {
        window.focus();
        setImmediate(() => {
            window.focus();
        });
    });

    return window;
}

// quit application when all windows are closed
app.on('window-all-closed', () => {
    // on macOS it is common for applications to stay open until the user explicitly quits
    app.quit();
});

app.on('activate', () => {
    // on macOS it is common to re-create a window even after all windows have been closed
    if (mainWindow === null) {
        mainWindow = createMainWindow();
    }
});


// create main BrowserWindow when electron is ready
app.on('ready', () => {

    app.setName('赤羽-文件列表');

    mainWindow = createMainWindow();
    let menu = Menu.buildFromTemplate(menuTpl);
    Menu.setApplicationMenu(menu);
});

